package com.sojson.config.proxy.servlet;

import javax.servlet.Servlet;

import org.mitre.dsmiley.httpproxy.ProxyServlet;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.HiddenHttpMethodFilter;

/**
 * 反向代理配置类
 *
 * @author liu
 * @date 2021-07-02
 */
@Configuration
public class ProxyServletConfig extends ProxyServlet {

    /***/
    private static final long serialVersionUID = 989721829193249463L;

    @Bean
    public ServletRegistrationBean<Servlet> yapi() {
        String path = "yapi";
        String port = "3000";

        // 配置路由策略
        ServletRegistrationBean<Servlet> servletRegistrationBean =
            new ServletRegistrationBean<>(new ProxyServletConfig(), "/*");
        // 这里的名字必须不一样
        servletRegistrationBean.setName(path);
        // 路由策略
        servletRegistrationBean.addInitParameter(ProxyServlet.P_TARGET_URI, "http://localhost:" + port);
        // 是否输出转发日志
        servletRegistrationBean.addInitParameter(ProxyServlet.P_LOG, "true");
        return servletRegistrationBean;
    }

    @Bean
    public ServletRegistrationBean<Servlet> sojson() {
        return init("sojson", "80");
    }

    @Bean
    public ServletRegistrationBean<Servlet> test() {
        return init("test", "8080");
    }

    @Bean
    public ServletRegistrationBean<Servlet> sojsonApi() {
        return init("sojson-api", "8080");
    }

    @Bean
    public ServletRegistrationBean<Servlet> work() {
        return init("work", "9001");
    }

    @Bean
    public ServletRegistrationBean<Servlet> rent() {
        return init("rent", "9002");
    }

    @Bean
    public ServletRegistrationBean<Servlet> sq() {
        return init("sq", "9003");
    }

    private ServletRegistrationBean<Servlet> init(String path, String port) {
        // 源路径和目标路径最好保持一致,不然一些页面中的相对路径图片会访问不到

        // 配置路由策略
        ServletRegistrationBean<Servlet> servletRegistrationBean =
            new ServletRegistrationBean<>(new ProxyServletConfig(), "/" + path + "/*");
        // 这里的名字必须不一样
        servletRegistrationBean.setName(path);
        // 路由策略
        servletRegistrationBean.addInitParameter(ProxyServlet.P_TARGET_URI, "http://localhost:" + port + "/" + path);
        // 是否输出转发日志
        servletRegistrationBean.addInitParameter(ProxyServlet.P_LOG, "true");
        return servletRegistrationBean;
    }

    /**
     * 关闭springboot 自带的 HiddenHttpMethodFilter 防止post提交的form数据流被提前消费
     *
     * @param filter
     * @return
     */
    // @Bean
    public FilterRegistrationBean<HiddenHttpMethodFilter> registration(HiddenHttpMethodFilter filter) {
        FilterRegistrationBean<HiddenHttpMethodFilter> registration = new FilterRegistrationBean<>(filter);
        registration.setEnabled(false);
        return registration;
    }

}